import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { walletApi } from '../../services/apiService';

// 解析URL查询参数
function useQuery() {
  return new URLSearchParams(useLocation().search);
}

const GenerateProof = () => {
  const navigate = useNavigate();
  const query = useQuery();
  const credentialIdFromUrl = query.get('credentialId');

  const [step, setStep] = useState(1); // 1: 选择凭证, 2: 选择证明类型, 3: 生成结果
  const [dids, setDids] = useState([]);
  const [credentials, setCredentials] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedDid, setSelectedDid] = useState('');
  const [selectedCredential, setSelectedCredential] = useState('');
  const [proofRequest, setProofRequest] = useState({
    type: 'ageProof', // ageProof, degreeProof, customProof
    minAge: 18,
    degreeType: '',
    major: '',
    customJson: '',
    skipRevocation: false
  });
  const [proofResult, setProofResult] = useState(null);
  const [generating, setGenerating] = useState(false);

  // 加载DID和凭证数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const [didsResponse, credentialsResponse] = await Promise.all([
          walletApi.listDids(),
          walletApi.listCredentials()
        ]);

        if (didsResponse.success && credentialsResponse.success) {
          setDids(didsResponse.dids);
          setCredentials(credentialsResponse.credentials);
          
          // 如果有DID，默认选择第一个
          if (didsResponse.dids.length > 0) {
            setSelectedDid(didsResponse.dids[0].id);
          }
          
          // 如果URL中有凭证ID，默认选择它
          if (credentialIdFromUrl) {
            setSelectedCredential(credentialIdFromUrl);
            setStep(2); // 直接跳到第2步
          } else if (credentialsResponse.credentials.length > 0) {
            setSelectedCredential(credentialsResponse.credentials[0].id);
          }
        } else {
          setError('获取数据失败');
        }
      } catch (error) {
        console.error('获取数据出错:', error);
        setError('获取数据时发生错误，请稍后再试');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [credentialIdFromUrl]);

  // 处理生成证明
  const handleGenerateProof = async () => {
    try {
      setGenerating(true);
      setError(null);
      
      // 准备证明请求
      let proofRequestData;
      
      if (proofRequest.type === 'ageProof') {
        proofRequestData = {
          id: `age-proof-${Date.now()}`,
          circuitId: 'credentialAtomicQuerySigV2',
          query: {
            allowedIssuers: ['*'],
            type: 'KYCAgeCredential',
            context: 'https://eduverse.example.com/schemas/kyc-age.jsonld',
            credentialSubject: {
              birthday: {
                $lt: calculateTargetDate(proofRequest.minAge)
              }
            }
          },
          challenge: Math.floor(Math.random() * 1000000).toString(),
          skipRevocation: proofRequest.skipRevocation
        };
      } else if (proofRequest.type === 'degreeProof') {
        const credentialSubject = {};
        
        if (proofRequest.degreeType) {
          credentialSubject.degreeType = {
            $eq: proofRequest.degreeType
          };
        }
        
        if (proofRequest.major) {
          credentialSubject.major = {
            $eq: proofRequest.major
          };
        }
        
        proofRequestData = {
          id: `degree-proof-${Date.now()}`,
          circuitId: 'credentialAtomicQuerySigV2',
          query: {
            allowedIssuers: ['*'],
            type: 'AcademicDegreeCredential',
            context: 'https://eduverse.example.com/schemas/academic-degree.jsonld',
            credentialSubject
          },
          challenge: Math.floor(Math.random() * 1000000).toString(),
          skipRevocation: proofRequest.skipRevocation
        };
      } else if (proofRequest.type === 'customProof') {
        try {
          proofRequestData = JSON.parse(proofRequest.customJson);
        } catch (e) {
          throw new Error('无效的JSON格式');
        }
      }
      
      // 调用API生成证明
      const response = await walletApi.generateProof(
        proofRequestData,
        selectedDid,
        selectedCredential
      );
      
      if (response.success) {
        setProofResult({
          proof: response.proof,
          circuitId: response.circuitId || proofRequestData.circuitId,
          request: proofRequestData
        });
        setStep(3);
      } else {
        setError(response.error || '生成证明失败');
      }
    } catch (error) {
      console.error('生成证明出错:', error);
      setError(`生成证明时发生错误: ${error.message}`);
    } finally {
      setGenerating(false);
    }
  };

  // 创建可验证演示
  const handleCreatePresentation = async () => {
    try {
      setGenerating(true);
      setError(null);
      
      const presentationData = {
        holderDid: selectedDid,
        zkProof: proofResult.proof,
        circuitId: proofResult.circuitId,
        challenge: proofResult.request.challenge,
        domain: window.location.hostname
      };
      
      const response = await walletApi.createPresentation(presentationData);
      
      if (response.success) {
        setProofResult(prev => ({
          ...prev,
          presentation: response.presentation
        }));
      } else {
        setError(response.error || '创建可验证演示失败');
      }
    } catch (error) {
      console.error('创建可验证演示出错:', error);
      setError(`创建可验证演示时发生错误: ${error.message}`);
    } finally {
      setGenerating(false);
    }
  };

  // 计算目标日期 (YYYYMMDD格式)
  const calculateTargetDate = (minAge) => {
    const today = new Date();
    const targetDate = new Date(
      today.getFullYear() - minAge,
      today.getMonth(),
      today.getDate()
    );
    return parseInt(
      targetDate.getFullYear().toString() +
      String(targetDate.getMonth() + 1).padStart(2, '0') +
      String(targetDate.getDate()).padStart(2, '0')
    );
  };

  if (loading) {
    return (
      <div className="loading-spinner">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">加载中...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="generate-proof">
      <div className="d-flex justify-content-between align-items-center mb-4">
        <h4 className="section-title">生成证明</h4>
        {step > 1 && (
          <button
            className="btn btn-outline-secondary"
            onClick={() => setStep(step - 1)}
          >
            <i className="bi bi-arrow-left me-2"></i>
            上一步
          </button>
        )}
      </div>

      {error && <div className="alert alert-danger">{error}</div>}

      <div className="card mb-4">
        <div className="card-body">
          <div className="mb-4">
            <div className="progress">
              <div 
                className="progress-bar" 
                role="progressbar" 
                style={{ width: `${(step / 3) * 100}%` }}
                aria-valuenow={step} 
                aria-valuemin="0" 
                aria-valuemax="3"
              >
                步骤 {step}/3
              </div>
            </div>
          </div>

          {step === 1 && (
            <div className="step-content">
              <h5 className="mb-4">选择身份和凭证</h5>
              
              {(dids.length === 0 || credentials.length === 0) && (
                <div className="alert alert-warning">
                  {dids.length === 0 ? (
                    <>
                      您还没有创建任何数字身份。
                      <button 
                        className="btn btn-warning btn-sm ms-2"
                        onClick={() => navigate('/wallet/dids/create')}
                      >
                        创建身份
                      </button>
                    </>
                  ) : credentials.length === 0 ? (
                    <>
                      您还没有任何凭证。
                      <button 
                        className="btn btn-warning btn-sm ms-2"
                        onClick={() => navigate('/wallet/credentials')}
                      >
                        管理凭证
                      </button>
                    </>
                  ) : null}
                </div>
              )}
              
              <div className="mb-3">
                <label htmlFor="selectDid" className="form-label">选择数字身份 (DID)</label>
                <select
                  id="selectDid"
                  className="form-select"
                  value={selectedDid}
                  onChange={(e) => setSelectedDid(e.target.value)}
                  disabled={dids.length === 0}
                >
                  {dids.map((did, index) => (
                    <option key={index} value={did.id}>
                      {did.method} | {did.id}
                    </option>
                  ))}
                </select>
              </div>
              
              <div className="mb-3">
                <label htmlFor="selectCredential" className="form-label">选择凭证</label>
                <select
                  id="selectCredential"
                  className="form-select"
                  value={selectedCredential}
                  onChange={(e) => setSelectedCredential(e.target.value)}
                  disabled={credentials.length === 0}
                >
                  {credentials.map((cred, index) => (
                    <option key={index} value={cred.id}>
                      {cred.type && Array.isArray(cred.type) && cred.type.length > 1
                        ? cred.type[cred.type.length - 1]
                        : cred.type || '未知类型'} | {cred.id}
                    </option>
                  ))}
                </select>
              </div>
              
              <div className="d-grid gap-2 mt-4">
                <button
                  className="btn btn-primary"
                  onClick={() => setStep(2)}
                  disabled={!selectedDid || !selectedCredential}
                >
                  下一步
                </button>
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="step-content">
              <h5 className="mb-4">选择证明类型</h5>
              
              <div className="mb-3">
                <div className="form-check">
                  <input
                    className="form-check-input"
                    type="radio"
                    name="proofType"
                    id="ageProof"
                    value="ageProof"
                    checked={proofRequest.type === 'ageProof'}
                    onChange={() => setProofRequest({...proofRequest, type: 'ageProof'})}
                  />
                  <label className="form-check-label" htmlFor="ageProof">
                    年龄证明
                  </label>
                </div>
                <div className="form-check">
                  <input
                    className="form-check-input"
                    type="radio"
                    name="proofType"
                    id="degreeProof"
                    value="degreeProof"
                    checked={proofRequest.type === 'degreeProof'}
                    onChange={() => setProofRequest({...proofRequest, type: 'degreeProof'})}
                  />
                  <label className="form-check-label" htmlFor="degreeProof">
                    学位证明
                  </label>
                </div>
                <div className="form-check">
                  <input
                    className="form-check-input"
                    type="radio"
                    name="proofType"
                    id="customProof"
                    value="customProof"
                    checked={proofRequest.type === 'customProof'}
                    onChange={() => setProofRequest({...proofRequest, type: 'customProof'})}
                  />
                  <label className="form-check-label" htmlFor="customProof">
                    自定义证明
                  </label>
                </div>
              </div>
              
              {proofRequest.type === 'ageProof' && (
                <div className="mb-3">
                  <label htmlFor="minAge" className="form-label">最小年龄</label>
                  <input
                    type="number"
                    className="form-control"
                    id="minAge"
                    value={proofRequest.minAge}
                    onChange={(e) => setProofRequest({...proofRequest, minAge: parseInt(e.target.value)})}
                    min="1"
                    max="120"
                  />
                  <div className="form-text">证明持有者年龄大于等于此值</div>
                </div>
              )}
              
              {proofRequest.type === 'degreeProof' && (
                <>
                  <div className="mb-3">
                    <label htmlFor="degreeType" className="form-label">学位类型</label>
                    <select
                      className="form-select"
                      id="degreeType"
                      value={proofRequest.degreeType}
                      onChange={(e) => setProofRequest({...proofRequest, degreeType: e.target.value})}
                    >
                      <option value="">选择学位类型（可选）</option>
                      <option value="BSc">学士 (BSc)</option>
                      <option value="BA">学士 (BA)</option>
                      <option value="MSc">硕士 (MSc)</option>
                      <option value="MA">硕士 (MA)</option>
                      <option value="PhD">博士 (PhD)</option>
                    </select>
                  </div>
                  <div className="mb-3">
                    <label htmlFor="major" className="form-label">专业</label>
                    <input
                      type="text"
                      className="form-control"
                      id="major"
                      value={proofRequest.major}
                      onChange={(e) => setProofRequest({...proofRequest, major: e.target.value})}
                      placeholder="专业名称（可选）"
                    />
                  </div>
                </>
              )}
              
              {proofRequest.type === 'customProof' && (
                <div className="mb-3">
                  <label htmlFor="customJson" className="form-label">自定义证明请求 (JSON)</label>
                  <textarea
                    className="form-control"
                    id="customJson"
                    rows="6"
                    value={proofRequest.customJson}
                    onChange={(e) => setProofRequest({...proofRequest, customJson: e.target.value})}
                    placeholder='{"id":"custom-proof","circuitId":"credentialAtomicQuerySigV2","query":{...}}'
                  />
                </div>
              )}
              
              <div className="mb-3 form-check">
                <input
                  type="checkbox"
                  className="form-check-input"
                  id="skipRevocation"
                  checked={proofRequest.skipRevocation}
                  onChange={(e) => setProofRequest({...proofRequest, skipRevocation: e.target.checked})}
                />
                <label className="form-check-label" htmlFor="skipRevocation">
                  跳过撤销检查
                </label>
              </div>
              
              <div className="d-grid gap-2 mt-4">
                <button
                  className="btn btn-primary"
                  onClick={handleGenerateProof}
                  disabled={generating || (proofRequest.type === 'customProof' && !proofRequest.customJson)}
                >
                  {generating ? (
                    <>
                      <span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                      生成中...
                    </>
                  ) : (
                    <>生成证明</>
                  )}
                </button>
              </div>
            </div>
          )}

          {step === 3 && proofResult && (
            <div className="step-content">
              <h5 className="mb-4">生成结果</h5>
              
              <div className="alert alert-success mb-4">
                <i className="bi bi-check-circle me-2"></i>
                证明已成功生成
              </div>
              
              <div className="card mb-4">
                <div className="card-header">证明详情</div>
                <div className="card-body">
                  <div className="mb-3">
                    <label className="form-label">电路ID:</label>
                    <div className="form-control bg-light">{proofResult.circuitId}</div>
                  </div>
                  <div className="mb-3">
                    <label className="form-label">请求ID:</label>
                    <div className="form-control bg-light">{proofResult.request.id}</div>
                  </div>
                  <div className="mb-3">
                    <label className="form-label">挑战值:</label>
                    <div className="form-control bg-light">{proofResult.request.challenge}</div>
                  </div>
                </div>
              </div>
              
              {!proofResult.presentation ? (
                <div className="d-grid gap-2 mt-4">
                  <button
                    className="btn btn-primary"
                    onClick={handleCreatePresentation}
                    disabled={generating}
                  >
                    {generating ? (
                      <>
                        <span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                        创建中...
                      </>
                    ) : (
                      <>创建可验证演示 (VP)</>
                    )}
                  </button>
                </div>
              ) : (
                <>
                  <div className="alert alert-success mb-4">
                    <i className="bi bi-check-circle me-2"></i>
                    可验证演示已创建成功
                  </div>
                  
                  <div className="d-grid gap-2 mt-4">
                    <button
                      className="btn btn-primary"
                      onClick={() => {
                        const vpJson = JSON.stringify(proofResult.presentation, null, 2);
                        navigator.clipboard.writeText(vpJson);
                        alert('可验证演示JSON已复制到剪贴板');
                      }}
                    >
                      <i className="bi bi-clipboard me-2"></i>
                      复制VP JSON
                    </button>
                    
                    <button
                      className="btn btn-outline-primary"
                      onClick={() => navigate('/wallet/credentials')}
                    >
                      返回凭证管理
                    </button>
                  </div>
                </>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default GenerateProof; 